import 'package:flutter_getx/app/data/api/api.dart';
import 'package:flutter_getx/app/service/user_info_service.dart';
import 'package:flutter_getx/app/util/dio/app_response.dart';
import 'package:flutter_getx/app/data/model/uer_info.dart';
import 'package:flutter_getx/app/service/dio_service.dart';
import 'package:get/get.dart';
import 'package:image_picker/image_picker.dart';

class MeController extends GetxController {
  DioService _dioService = Get.find();
  UserInfoService userInfoService = Get.find();
  Api api = new Api();


  Future<void> getUserInfo() async {
    if (userInfoService.userInfo.value.id == null) {
      return;
    }
    AppResponse res =
        await _dioService.get("/user", queryParameters: {'id': userInfoService.userInfo.value.id});
    if (res.ok) {
      userInfoService.userInfo.value = UserInfo.fromJson(res.data);
    }
  }

  Future getImageFromGallery() async {
    PickedFile? image = await ImagePicker().getImage(source: ImageSource.gallery);
    if (image == null) {
      return;
    }
    String path = image.path;
    var filename = path.substring(path.lastIndexOf("/") + 1, path.length);
    var url = await api.updateAvatar(userInfoService.userInfo.value.id!, image, filename);
    if (url != null) {
      userInfoService.userInfo.value.avatar = url;
      userInfoService.userInfo.refresh();
    }
  }

  @override
  void onInit() {
    getUserInfo();
    super.onInit();
  }

  @override
  void onReady() {
    super.onReady();
  }

  @override
  void onClose() {}
}
